const pool = require('../config/database');

class Favorite {
  // 添加收藏
  static async add(userId, carId) {
    try {
      const [result] = await pool.execute(
        'INSERT INTO favorites (user_id, car_id) VALUES (?, ?)',
        [userId, carId]
      );
      return result.insertId;
    } catch (error) {
      if (error.code === 'ER_DUP_ENTRY') {
        throw new Error('该车辆已在收藏列表中');
      }
      throw error;
    }
  }

  // 移除收藏
  static async remove(userId, carId) {
    const [result] = await pool.execute(
      'DELETE FROM favorites WHERE user_id = ? AND car_id = ?',
      [userId, carId]
    );
    return result.affectedRows > 0;
  }

  // 获取用户的收藏列表
  static async findByUser(userId) {
    const [rows] = await pool.execute(
      `SELECT c.*, u.name as seller_name, u.avatar as seller_avatar,
              (SELECT image_url FROM car_images WHERE car_id = c.id AND is_main = TRUE LIMIT 1) as main_image
       FROM favorites f
       JOIN cars c ON f.car_id = c.id
       LEFT JOIN users u ON c.seller_id = u.id
       WHERE f.user_id = ? AND c.status = 'approved'
       ORDER BY f.created_at DESC`,
      [userId]
    );

    return rows;
  }

  // 检查是否已收藏
  static async exists(userId, carId) {
    const [rows] = await pool.execute(
      'SELECT id FROM favorites WHERE user_id = ? AND car_id = ?',
      [userId, carId]
    );
    return rows.length > 0;
  }
}

module.exports = Favorite;